<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class System extends Model
{
    protected $dateFormat = 'U';
    //
    protected $table = "lexiang_system";

    public function set($k,$value,$time=0){
    	try {
    		$this_ = $this->where('option',$k)->first();
	    	if(!$this_){
	    		$this_ = $this;
	    	}
	    	$this_->option = $k;
	    	$this_->value = $value;
	    	$this_->out_time = $time;
	    	if($this_->save()){
	    		return [
	    			'success'=>true,
	    			'code'=>'000',
	    			'message'=>'设置成功',
	    			'data'=>[
	    				'option'=>$k,
	    				'value'=>$value,
	    				'out_time'=>$time
	    			]
	    		];
	    	}else{
	    		return [
	    			'success'=>false,
	    			'code'=>'006',
	    			'message'=>'设置出错'
	    		];
	    	}
    	} catch (\Exception $e) {
    		return [
    			'success'=>false,
    			'code'=>'006',
    			'message'=>'设置出错'
    		];
    	}
    }

    public function editContent($data)
    {
        $this_ = $this->where('option',$data['option'])->first();
        if(!$this_){
            $this_ = $this;
        }
        $this_->option = $data['option'];
        $this_->value = '';
        $this_->content = $data['content'];
        $this_->out_time = 0;
        if($this_->save()){
            return [
                'success'=>true,
                'code'=>'000',
                'message'=>'设置成功',
                'data'=>[
                    'option'=>$data['option'],
                    
                    'content'=>$data['content'],
                    'out_time'=>0
                ]
            ];
        }else{
            return [
                'success'=>false,
                'code'=>'006',
                'message'=>'设置出错'
            ];
        }
    }

    public function get($k,$fun='getToken')
    {
    	$data = $this->where('option',$k)->first();
    	if(!$data){
			return $this->$fun();
    	}
    	if((time() - $data->getOriginal('updated_at')) > $data->out_time){
    		return $this->$fun();
    	}

    	return [
			'success'=>true,
			'code'=>'000',
			'message'=>'获取成功',
			'data'=>$data
		];
    }

    private function getToken()
    {
    	$appid = ENV('CLIENT_WXAPPID');
        $secret = ENV('CLIENT_WXSECRET');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $data = json_decode(curl_get($url),true);
        return $this->set('pro_access_token',$data['access_token'],$data['expires_in']);
    }

    private function getGzhToken()
    {
        $appid = ENV('GZHWXAPPID');
        $secret = ENV('GZHAPPSECRET');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $data = json_decode(curl_get($url),true);
        return $this->set('gzh_access_token',$data['access_token'],$data['expires_in']);
    }
}
